from time import time
from Common.ReadYaml import get_yml_data
from Common.HttpApi import Api

class UserActionToken:
    def __init__(self):
        self.api = Api(host='api.weixin.qq.com')
        self.token_info = {}

    def get_token(self):
        current_time = time()
        # Check if the token exists and is not older than 2 hours
        if self.token_info and (current_time - self.token_info['timestamp']) < 7200:
            print('Using existing token')
            return self.token_info['access_token']

        url = 'cgi-bin/token'
        result = self.api.request('get', url, payload=get_yml_data('Action', 'token', 'get_token')[0]['palayod']).json()
        self.token_info = {
            'access_token': result['access_token'],
            'expires_in': result['expires_in'],
            'timestamp': current_time  # Update the token timestamp when a new token is obtained
        }
        return self.token_info['access_token']

if __name__ == '__main__':
    user_token = UserActionToken()
    access_token = user_token.get_token()
    print('Access token:', access_token)
